#include <texture.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <targa.h>
#include <program_manager.h>

#define TEXTURE_PROGRAM	PROGRAM_MANAGER->getProgram("texture")

GLint Texture::total = 0;

Texture::Texture()
: id(0)
, x(0.0f)
, y(0.0f)
{

}

Texture::~Texture()
{
	if (id > 0)
	{
		glDeleteBuffers(1, &id);
	}

}

int Texture::load(const char * filename)
{

	tga_image img;
	tga_result result;
	
	result = tga_read(&img, filename);
	if (result != TGA_NOERR)
	{
		printf("Error tga\n");
		return 1;
	}

	width = img.width;
	height = img.height;
	tga_swap_red_blue(&img);
	glGenTextures(1, &id);
	glBindTexture(GL_TEXTURE_2D, id);

	glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, width, height, 0, GL_RGBA, GL_UNSIGNED_BYTE, img.image_data);
	glTexParameteri ( GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR );
	glTexParameteri ( GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR );
	glTexParameteri ( GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE );
	glTexParameteri ( GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE );

	tga_free_buffers(&img);

	return 0;
}


void Texture::draw()
{
	//PROGRAM_MANAGER->debug();

	TEXTURE_PROGRAM->use();
	

	GLint viewport_size[4];
	glGetIntegerv(GL_VIEWPORT, viewport_size);

	float real_x_pos = (x/((float)viewport_size[2]));
	
	float real_y_pos = (y/((float)viewport_size[3]));

	float real_width = 1.0f/(((float)width)/((float)viewport_size[2]));
	float real_height = 1.0f/(((float)height)/((float)viewport_size[3]));

	GLfloat vVertices[] = { 
						-1.0,  1.0f, 0.0f,  // Position 0
						-real_x_pos,  -real_y_pos,        // TexCoord 0 
					    
						-1.0, -1.0f, 0.0f,  // Position 1
						-real_x_pos,  real_height - real_y_pos,        // TexCoord 1
						
						1.0, -1.0f, 0.0f,  // Position 2
						real_width - real_x_pos ,  real_height - real_y_pos,        // TexCoord 2
					    
						1.0, 1.0f, 0.0f,  // Position 3
						real_width - real_x_pos,  - real_y_pos        // TexCoord 3
					 };

	GLushort indices[] = { 0, 1, 2, 0, 2, 3 };


	glVertexAttribPointer(TEXTURE_PROGRAM->getShaderIO("a_position"), 3, GL_FLOAT, 
					   GL_FALSE, 5 * sizeof(GLfloat), &vVertices[0]);

	glVertexAttribPointer(TEXTURE_PROGRAM->getShaderIO("a_texCoord"), 2, GL_FLOAT,
					   GL_FALSE, 5 * sizeof(GLfloat), &vVertices[3]);
	
	glEnableVertexAttribArray(TEXTURE_PROGRAM->getShaderIO("a_position"));
	glEnableVertexAttribArray(TEXTURE_PROGRAM->getShaderIO("a_texCoord"));

	// Bind the base map
	glActiveTexture ( GL_TEXTURE0);
	glBindTexture ( GL_TEXTURE_2D, getID());

	// Set the base map sampler to texture unit to 0
	glUniform1i (TEXTURE_PROGRAM->getShaderIO("s_baseMap"), 0 );

	glDrawElements ( GL_TRIANGLES, 6, GL_UNSIGNED_SHORT, indices );
}
